package club.zhcs.cms.module.admin.settings;

import org.apache.shiro.authz.annotation.RequiresRoles;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.lang.ContinueLoop;
import org.nutz.lang.Each;
import org.nutz.lang.ExitLoop;
import org.nutz.lang.Lang;
import org.nutz.lang.LoopException;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import club.zhcs.cms.bean.system.config.Config;
import club.zhcs.cms.biz.config.ConfigService;

import com.kerbores.nutz.module.base.AbstractBaseModule;
import com.kerbores.utils.entries.Result;

/**
 * 
 * @author Kerbores(kerbores@gmail.com)
 *
 * @project cms
 *
 * @file SettingsModule.java
 *
 * @description 网站配置
 *
 * @copyright 内部代码,禁止转发
 *
 * @time 2016年5月12日 下午2:29:43
 *
 */
@At("admin/config")
public class SettingsModule extends AbstractBaseModule {

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.kerbores.nutz.module.base.AbstractBaseModule#_getNameSpace()
	 */
	@Override
	public String _getNameSpace() {
		return "";
	}

	@Inject
	ConfigService configService;

	@At("/")
	@Ok("beetl:pages/admin/config/config.html")
	@RequiresRoles("admin")
	public Result config() {
		final NutMap data = NutMap.NEW();
		Lang.each(configService.queryAll(), new Each<Config>() {

			@Override
			public void invoke(int paramInt1, Config config, int paramInt2) throws ExitLoop, ContinueLoop, LoopException {
				data.put(config.getName(), config.getValue());
			}
		});
		return Result.success().addData("configs", data);
	}

	@At
	@RequiresRoles("admin")
	public Result save(@Param("..") final NutMap map) {

		Lang.each(map.keySet(), new Each<String>() {

			@Override
			public void invoke(int arg0, String key, int arg2) throws ExitLoop, ContinueLoop, LoopException {
				Config config = new Config();
				config.setName(key);
				config.setValue(map.getString(key));
				if (configService.fetch(Cnd.where("name", "=", config.getName())) == null) {
					if (configService.save(config) == null) {
						throw new LoopException(new RuntimeException("保存失败!"));
					}
				} else {
					if (configService.update(config, Cnd.where("name", "=", config.getName()), "value") != 1) {
						throw new LoopException(new RuntimeException("更新失败!"));
					}
				}
			}
		});

		return Result.success();
	}
}
